<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: niuzhixin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Sub;

use AuctionCore\CarDealer\Dealer;
use AuctionCore\System\AuctionException;
/**
* 订阅操作类
* @author  niuzhixin
*/
Class SubOrder{

    /**
     * 车商id
     * @var      int
     */
    public $dealer_id;

    /**
     * 构造,初始化"车商id"
     * @param    int $dealer_id 车商id
     */
    public function __construct($dealer_id)
    {
        $this->dealer_id = $dealer_id;
    }
    /**
     * 新增订阅
     * @param array $data
     */
        public function add($data=array()){
            $res = M('subscribe')->add($data);
            return $res;
        }
    /**
     * 新增订阅参数
     * @param array $data
     */
    public function addall($data=array()){
        $res = M('subscribe_key')->addAll($data);
        return $res;
    }
    /**
     * 处理订阅参数
     * @param array $data
     */
    public function set_sub_key($data,$post,$type){
        $list = array();
        for($i=0;$i<count($post);$i++){
            $list[$i] = $data;
            $list[$i]['key_name'] = $post[$i];
            $list[$i]['key_type'] = $type;
        }
        return $list;
    }

    /**
     * 删除订阅
     * @param int $sid
     */
        public function delete($sid){
            M()->startTrans();
            $res_sub = M('subscribe')->where("sid='$sid'")->delete(); //删除订阅名称
            $res_sub_key = M('subscribe_key')->where("sid='$sid'")->delete(); //删除订阅参数
            $res_sub_order = M('subscribe_order')->where("sid='$sid'")->delete();  //删除订阅推送上拍记录
            if($res_sub !==false && $res_sub_key!==false && $res_sub_order !== false){
                M()->commit();
            }else{
                M()->rollback();
            }
        }
    /**
     * 查询订阅参数
     * @param int $sid
     */
    public function sel_key_type($sid){
        $info = M('subscribe_key')->where("sid='$sid'")->select();
        return $info;
    }
    /**
     * 查询订阅上拍中的拍单
     * @param int $sid
     */
    public function sel_order($sid){
        $order_id = M('subscribe_order')->where("sid='$sid'")->getField('order_id',true);
        return $order_id;
    }
    /**
     * 查询车商订阅内容;
     * @param int $sid
     */
    public function sel_sub($dealer_id){
        $info = M('subscribe')->where("dealer_id='".$dealer_id."'")->order("sid DESC")->select();
        return $info;
    }
    /**
     * 查询车商订阅个数;
     * @param int $dealer_id
     */
    public function sel_sub_count($dealer_id){
        $total = M('subscribe')->where("dealer_id='".$dealer_id."'")->count();
        return $total;
    }
    /**
     * 查询车商订阅上拍中的车辆数量;
     * @param int $sid
     */
    public function sel_order_count($sid){
        $total = M('subscribe_order')->alias('s')->join(C('DB_PREFIX') . "order o On s.order_id=o.order_id")->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where("s.sid='$sid' and o.status in (3,301,4)")->count();
        return $total;
    }
    /**
     * 查询订阅拍单表中的上拍车辆
     * @param int $orderid
     */
    public function get_index_order($sid) {
        $cm = new \AuctionCore\CarResource\CarModel();
        $addr = new \AuctionCore\Other\Address();
        $dObj = new \AuctionCore\CarDealer\Dealer($this->dealer_id);
        $order_id = $this->sel_order($sid);
        $map = array();
        $map['o.order_id'] = array('in',(is_array($order_id) && $order_id)?$order_id:array(0) );
        $map['o.status'] = array('in','3,301,4');
        //dump($map);
        //计算符合条件的记录总数
        $total = M('subscribe_order')->alias('s')->join(C('DB_PREFIX') . "order o On s.order_id=o.order_id")->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os On os.scene_id=o.scene_id")->where("s.sid='$sid' and o.status in (3,301,4)")->count();
        $cols = "o.order_id,o.order_no,o.scene_id,o.status,os.starttime,
                    o.bid_start_price,o.bidding_best_price,o.bidding_start_time,o.act_elapsed_time,o.est_elapsed_time,o.coupon,o.rank,o.is_timing_order,o.show_reserve_price,
                    c.series_id,c.car_id,c.car_no,c.reg_city,c.first_reg_date,c.pointer_mileage,c.location_area,
                    c.plate_prefix,c.plate_suffix,c.composite_state,c.accident_level,c.car_cc,c.turbo,c.gearbox,
                    UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time
                    ";
        $res = M('order')->alias('o')->field($cols)->join(C('DB_PREFIX') . "cars c On o.car_id=c.car_id")
            ->join(C('DB_PREFIX') . "order_scene os ON os.scene_id=o.scene_id")
            ->where($map)->order("o.bid_start_time desc")->limit('2')->select();
        //echo M()->getLastSql();die;  "order_id ='$order_id' and o.status in (4,301,3) "
        $list = array();
        foreach ($res as $key => $value) {
            $list[$key]['order_id'] = $value['order_id'];
            $list[$key]['order_no'] = $value['order_no'];
            //品牌车系车型
            $series = $cm->get_model_by_id($value['series_id'], 'series');
            //品牌车系车型
            $location_area = '['.$addr->get_name_by_code($value['location_area']).']';
            $list[$key]['car_name'] = $location_area.$series['name'] . ' ' . $value['car_cc'] . ($value['turbo'] ? 'T' : 'L') . ' ' . C('GEARBOX.' . $value['gearbox']);
            //初登日期
            $list[$key]['first_reg_date'] = date('Y年m月', strtotime($value['first_reg_date']));
            //公里数格式转换
            $list[$key]['pointer_mileage'] = convert_mileage($value['pointer_mileage']);

            $list[$key]['plate_number'] = C('PLATE_PREFIX.' . $value['plate_prefix']) . substr($value['plate_suffix'], 0, 1);

            $list[$key]['desc'] = $list[$key]['first_reg_date'].'初登/'.$list[$key]['pointer_mileage'].'万公里/'.$list[$key]['plate_number'];

            ///汽车缩略图(不加oss图片处理参数)
            $car = new \AuctionCore\CarResource\Car($value['car_id']);
            $cond = "car_id='" . $value['car_id'] . "' AND pic_key='p_left_front45'";
            $pics = $car->get_pics('car_pictures', $cond);
            $list[$key]['img'] = $pics[0]['pic_url'];
            //是否关注
            $list[$key]['is_followed'] = $dObj->is_followed($value['order_id']) ? 1 : 0 ;
            //车况等级
            $list[$key]['composite_level'] = $value['composite_state'] . $value['accident_level'];
            //是否能用代金券
            $list[$key]['use_coupon'] = $value['coupon'] > 0 ? true : false;
            ///拍单状态
            $list[$key]['bidding_best_dealer_id'] = $value['bidding_best_dealer_id'];
            $list[$key]['state'] = $value['status'];
            //起拍价
            $list[$key]['bid_start_price'] = $value['bid_start_price'];

            switch ($value['status']) {
                case '3':
                    $list[$key]['status_cn'] = '投标中';
                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);
                    //交易服务费
                    $list[$key]['commision'] = $my_last_bid_price>0? get_commision($my_last_bid_price,$value['starttime']):get_commision($value['bid_start_price'],$value['starttime']);
                    //当前价
                    $price = $my_last_bid_price>0 ?$my_last_bid_price:$value['bid_start_price'];
                    break;
                case '301':
                    $list[$key]['status_cn'] = '待竞拍';
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bid_start_price']);
                    //当前价
                    $price = $value['bid_start_price'];
                    break;
                case '4':
                    $list[$key]['status_cn'] = '竞拍中';

                    $my_last_bid_price = $dObj->get_my_last_bid_price($value['order_id']);
                    $list[$key]['my_last_bid_price'] = floatval($my_last_bid_price);

                    $my_last_bidding_price = $dObj->get_my_last_bidding_price($value['order_id']);
                    $list[$key]['my_last_bidding_price'] = floatval($my_last_bidding_price);
                    //交易服务费
                    $list[$key]['commision'] = get_commision($value['bidding_best_price']>0? $value['bidding_best_price']:$value['bid_start_price']);
                    //当前价
                    $price = $value['bidding_best_price']>$value['bid_start_price']?$value['bidding_best_price']:$value['bid_start_price'];
                    break;
            }
            //当前价格
            $list[$key]['price'] = intval($price);
            //交付服务费
            $list[$key]['transfer_fee'] = intval($value['transfer_fee']);
            /*************************计算剩余时间**********************************/
            //结束时间（竞拍结束时间、投标结束时间 时间戳）
            $list[$key]['starttime'] = strtotime($value['starttime'])*1000;
            $list[$key]['bidding_start_time'] = strtotime($value['bidding_start_time'])*1000;
            $list[$key]['act_elapsed_time'] = $value['act_elapsed_time']*1000;
            $list[$key]['est_elapsed_time'] = $value['est_elapsed_time']*1000;

            //是否显示保留价
            $list[$key]['show_reserve_price'] = $value['show_reserve_price']>0?true:false;
        }
        return $list;
    }
}
